package com.kws.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.FeedbackMessageEntity;
import com.kws.merchant.domain.po.FeedbackMessagePo;
import com.kws.merchant.domain.po.UserMessagePo;
import com.kws.merchant.domain.vo.*;
import com.kws.merchant.mapper.FeedbackMessageMapper;
import com.kws.merchant.service.FeedbackMessageService;
import com.kws.system.api.domain.SysUser;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/11/19 9:32
 * @Version: 1.0
 */
@Service
public class FeedbackMessageServiceImpl extends ServiceImpl<FeedbackMessageMapper, FeedbackMessageEntity> implements FeedbackMessageService {

    @Override
    public boolean addFeedbackMessage(FeedbackMessagePo feedbackMessagePo) {
        FeedbackMessageEntity feedbackMessageEntity = new FeedbackMessageEntity();
        feedbackMessageEntity.setFeedbackMessage(feedbackMessagePo.getFeedbackMessage());
        feedbackMessageEntity.setUserId(SecurityUtils.getUserId());
        StringBuilder sb = new StringBuilder();
        for (String img : feedbackMessagePo.getFeedbackImg()) {
            sb = sb.append(img).append("kws:");
        }
        //去掉最后的kws:
        feedbackMessageEntity.setFeedbackImg(sb.substring(0, sb.length() - 4));
        return this.save(feedbackMessageEntity);
    }

    @Override
    public List<ServeMessageVo> getUserServeMessage() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        //客服消息
        List<MerchantUserChatVo> userServeMessage = baseMapper.getUserServeMessage(userId);
        Map<Long, List<MerchantUserChatVo>> collect = userServeMessage.stream().collect(Collectors.groupingBy(MerchantUserChatVo::getSendUser));
        ArrayList<ServeMessageVo> serveMessageVos = new ArrayList<>();
        if (collect != null){
            for (Map.Entry<Long, List<MerchantUserChatVo>> entry : collect.entrySet()) {
                ServeMessageVo serveMessageVo = new ServeMessageVo();
                serveMessageVo.setMerchantId(entry.getKey());
                List<MerchantUserChatVo> value = entry.getValue();
                MerchantUserChatVo merchantUserChatVo = value.stream().max(Comparator.comparing(MerchantUserChatVo::getCreateTime)).get();
                String content = merchantUserChatVo.getContent();
                JSONObject jsonObject = JSON.parseObject(content);
                serveMessageVo.setContent(jsonObject.getString("content"));
                serveMessageVo.setCreateTime(merchantUserChatVo.getCreateTime());
                serveMessageVo.setStatus(merchantUserChatVo.getStatus());
                serveMessageVo.setMessageCount(value.size());
                serveMessageVo.setMerchantImg(jsonObject.getString("sendUserAvatar"));
                serveMessageVo.setMerchantName(jsonObject.getString("sendUserName"));
                serveMessageVos.add(serveMessageVo);
            }
        }
        return serveMessageVos;
    }

    @Override
    public Page<LogisticsVo> getLogisticsMessage(UserMessagePo userMessagePo) {
        userMessagePo.setPageSize((userMessagePo.getPageSize() - 1) * userMessagePo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Long count = baseMapper.getLogisticsMessageCount(userId);
        Page<LogisticsVo> page = new Page<>(userMessagePo.getPageSize(), userMessagePo.getTotalPage(), count);
        if (count > 0) {
            List<MerchantUserChatVo> logisticsMessage = baseMapper.getLogisticsMessage(userId, userMessagePo.getPageSize(), userMessagePo.getTotalPage());
            ArrayList<LogisticsVo> serveMessageVos = new ArrayList<>();
            for (MerchantUserChatVo merchantUserChatVo : logisticsMessage) {
                String content = merchantUserChatVo.getContent();
                LogisticsVo logisticsVo = JSON.parseObject(content, LogisticsVo.class);
                serveMessageVos.add(logisticsVo);
            }
            page.setRecords(serveMessageVos);
        }
        return page;
    }

    @Override
    public Page<NoticeVo> getNoticeMessage(UserMessagePo userMessagePo) {
        userMessagePo.setPageSize((userMessagePo.getPageSize() - 1) * userMessagePo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Long count = baseMapper.getNoticeMessageCount(userId);
        Page<NoticeVo> page = new Page<>(userMessagePo.getPageSize(), userMessagePo.getTotalPage(), count);
        if (count > 0) {
            List<MerchantUserChatVo> logisticsMessage = baseMapper.getNoticeMessage(userId, userMessagePo.getPageSize(), userMessagePo.getTotalPage());
            List<NoticeVo> noticeVoList = new ArrayList<>();
            for (MerchantUserChatVo merchantUserChatVo : logisticsMessage) {
                String content = merchantUserChatVo.getContent();
                NoticeVo noticeVo = JSON.parseObject(content, NoticeVo.class);
                noticeVoList.add(noticeVo);
            }
            page.setRecords(noticeVoList);
        }
        return page;
    }

    @Override
    public MessageCountVo getUserMessageCount() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        MessageCountVo messageCountVo = new MessageCountVo();
        List<MerchantUserChatVo> userMessageCount = baseMapper.getUserMessageCount(userId);
        if (userMessageCount != null && userMessageCount.size() > 0) {
            Map<Integer, Long> messageCounts = userMessageCount.stream()
                    .collect(Collectors.groupingBy(MerchantUserChatVo::getMessageType, Collectors.counting()));

            messageCountVo.setServeCount(messageCounts.getOrDefault(4, 0L).intValue());
            messageCountVo.setLogisticsCount(messageCounts.getOrDefault(1, 0L).intValue());
            messageCountVo.setNoticeCount(messageCounts.getOrDefault(5, 0L).intValue());
        }
        return messageCountVo;
    }

    @Override
    public boolean readMessage(Long sendUser) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        return baseMapper.readMessage(sendUser, sysUser.getUserId());
    }
}
